<template>
  <div class="main-window">
    <div class="title-box">
      <input v-model="article.title" type="text" class="title" placeholder="请输入标题....">
      <el-button v-if="!isUpdate" id="btn" type="primary" icon="el-icon-edit" @click="openDialog" />
      <el-button v-if="isUpdate" id="btn" type="success" icon="el-icon-edit" @click="openDialog" />
    </div>
    <mavon-editor
      ref="md"
      v-model="article.content"
      v-loading="isUploading"
      :ishljs="true"
      :placeholder="'请在此处编辑···'"
      :toolbars="toolbars"
      :toolbars-background="'#f9f9f9'"
      style="height: calc(100vh - 50px)"
      :code-style="codeStyle"
      @imgAdd="$imgAdd"
      @imgDel="$imgDel"
      @save="openDialog"
    />
    <el-dialog :title="`发布文章：${article.title}`" :visible.sync="showCreateDialog" width="40%">
      <el-form v-loading="isUploading" label-position="left" label-width="100px">
        <el-form-item label="标签：" style="width:fit-content;">
          <el-tag
            v-for="tag in article.tags"
            :key="tag"
            closable
            :disable-transitions="false"
            style="border: solid 1px #F2F6FC"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputTagVisible"
            ref="saveTagInput"
            v-model="inputTag"
            size="small"
            class="input-new-tag"
            @keyup.enter.native="handleTagInputConfirm"
            @blur="handleTagInputConfirm"
          />
          <el-button v-else v-show="TagAddVisible" class="button-new-tag" size="small" @click="showTagInput">+新标签</el-button>
          <div class="tagContain" style="border: solid 1px #F2F6FC;margin-left:10px">
            <transition name="fade" mode="in-out">
              <div v-show="tagVisible" class="tag_container">
                <el-tag
                  v-for="(item,index) in tags"
                  v-show="article.tags.indexOf(item)===-1"
                  id="tagBtn"
                  :key="item"
                  type="success"
                  style="cursor: pointer;margin-left: 10px;margin-right: 30px"
                  size="mini"
                  @click="clickTag(item,index)"
                >
                  {{ item }}
                </el-tag>
              </div>
            </transition>
          </div>
          <el-autocomplete
            v-show="TagAddVisible"
            v-model="queryTag"
            :fetch-suggestions="querySearchAsync"
            placeholder="搜索所有标签"
            value-key="value"
            @select="clickTag"
          />
        </el-form-item>
        <el-form-item label="主题：" :rules="{required:true,message:'主题不能为空'}">
          <el-cascader v-model="article.category" :options="categories" :show-all-levels="false" @change="selectCategory" />
          <el-button type="text" class="add-category-btn" style="margin-left: 20px" @click="showAddCategory = true;article.category=''">自定义主题</el-button>
        </el-form-item>
        <transition name="el-zoom-in-top">
          <el-form-item v-show="showAddCategory && !article.category" label="新主题：">
            <el-input v-model="article.newCategory" placeholder="创建新主题的名称" />
          </el-form-item>
        </transition>
        <el-form-item label="摘要：" :rules="{required:true,message:'文章摘要不能为空'}">
          <el-input v-model="article.tabloid" type="textarea" rows="4" placeholder="填写内容简介" />
        </el-form-item>
        <!-- 图片上传 -->
        <el-form-item label="封面">
          <el-radio v-model="coverImgUploadWay" label="本地上传">本地上传</el-radio>
          <el-radio v-model="coverImgUploadWay" label="图片url上传">图片url上传</el-radio>
          <el-radio v-model="coverImgUploadWay" label="图库上传">图库上传</el-radio>
          <el-upload
            v-show="coverImgUploadWay==='本地上传'"
            class="avatar-uploader"
            action="http://localhost:8080/toUpload/uploadImg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeUpload"
            :on-progress="uploaded"
          >
            <transition name="el-fade-in-linear" mode="in-out">
              <img v-if="article.coverImg" :src="article.coverImg" class="avatar" alt="" @error="handlerImgError">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </transition>
          </el-upload>
          <loading
          <transition name="el-fade-in-linear" mode="out-in">
            <div v-if="coverImgUploadWay==='图片url上传'">
              <div style="display: inline">
                <el-input v-model="updateImgByUrl" style="width: 80%;margin-right: 4%;margin-bottom: 20px" placeholder="此处输入图片的url地址..." />
                <el-button type="primary" :loading="uploadingImg" @click="submitByUrl">上传</el-button>
              </div>
              <img :src="article.coverImg===''?require('../../assets/img/de.png'):article.coverImg" class="avatar" alt="" @error="handlerImgError">
            </div>
          </transition>
          <transition name="el-fade-in-linear" mode="in-out">
            <div v-if="coverImgUploadWay==='图库上传'">
              <div style="display: inline">
                <el-input v-model="article.coverImg" style="width: 80%;margin-right: 4%;margin-bottom: 20px" placeholder="图库中图片的url链接" />
              </div>
              <img :src="article.coverImg===''?require('../../assets/img/de.png'):article.coverImg" class="avatar" alt="" @error="handlerImgError">
            </div>
          </transition>
        </el-form-item>
        <el-form-item label="作者：" :rules="{required:true,message:'作者名称不能为空值'}">
          <el-input v-model="article.author" type="text" placeholder="填写作者名称" />
        </el-form-item>
        <el-form-item label="创作来源：">
          <el-radio v-model="article.type" label="原创" border>原创</el-radio>
          <el-radio v-model="article.type" label="转载" border>转载</el-radio>
        </el-form-item>
        <transition name="el-zoom-in-top" mode="in-out">
          <el-form-item v-show="article.type==='转载'" label="转载自">
            <el-input v-model="article.reprintURL" placeholder="请输入链接" />
          </el-form-item>
        </transition>
      </el-form>
      <span slot="footer">
        <el-button v-if="isUpdate" type="danger" @click="reset">退出更新<i class="el-icon-back" style="margin-left: 10px" /></el-button>
        <el-button type="info" :loading="uploadingImg" @click="article.status='draft';handleSubmit()">存草稿<i class="el-icon-tickets" /> </el-button>
        <el-button v-if="!isUpdate" :loading="uploadingImg" type="success" @click="article.status='published';handleSubmit()">发布<i class="el-icon-upload el-icon--right" style="margin-left: 10px" /></el-button>
        <el-button v-if="isUpdate" :loading="uploadingImg" type="success" @click="article.status='published';handleSubmit()">更新<i class="el-icon-upload el-icon--right" style="margin-left: 10px" /></el-button>
      </span>
    </el-dialog>
    <float-window v-show="article.id!==''" :id="article.id" :is-check="true" :is-update="isUpdate" @reset="reset" />
  </div>
</template>

<script>
import { uploadImg, uploadImgByUrl } from '@/api/upload'
import { Message } from 'element-ui'
import { createTag, getAllTags } from '@/api/tag'
import store from '@/store/modules/article'
import { createNewCategory, getAllCategory } from '@/api/category'
import { getList, updateArticle, uploadArticle } from '@/api/table'
import FloatWindow from '@/components/myComponent/floatWindow'
import Loading from '@/views/loading/loading'

const { openMdFIleLocal } = require('@/api/table')

export default {
  name: 'Index',
  components: { Loading, FloatWindow },
  data() {
    return {
      // 前一个还没上传完成
      isUploading: false,
      // 图片上传的地址
      updateImgByUrl: '',

      // 图片上传方法
      coverImgUploadWay: '本地上传',
      // 图片正在上传
      uploadingImg: false,
      codeStyle: 'tomorrow-night-blue',
      isActive: false,
      // 新建还是修改
      isUpdate: false,
      // 创建栏是否可见
      showCreateDialog: false,
      content: '',
      // 标签-----------------------------------
      // 标签信息,从后端获取
      tags: [],
      // 查询到的标签信息
      queryTag: '',
      // 标签栏是否可见
      tagVisible: false,
      // 添加一个新标签内容条是否可见
      TagAddVisible: true,
      // 输入新标签是否可见
      inputTagVisible: false,
      // 添加的新标签的内容
      inputTag: '',
      // --------------------------------------
      // 分类信息
      categories: [],
      // 分类栏是否可见
      categoryVisible: false,
      // 是否展示添加分类
      showAddCategory: false,
      article: {
        title: '',
        content: '',
        category: '',
        tags: [],
        tabloid: '',
        type: true,
        author: '',
        newCategory: '',
        status: '',
        reprintURL: '',
        id: '',
        coverImg: ''
      },
      // 参数
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: false, // 全屏编辑
        readmodel: false, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: false, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: false // 预览
      }
    }
  },
  created() {
    const articleId = this.$route.query.articleId
    if (articleId !== '' && articleId != null) {
      this.isActive = true
      getList({ articleId }).then((res) => {
        console.log(res)
        store.commit('updateArticle', res.data.data.list[0])
        this.article = store.getters.getArticle
        this.article.id = articleId
        store.commit('updateIsUpdate', true)
        this.isActive = false
        this.isUpdate = true
        if (this.article.tags.length >= 5) {
          this.TagAddVisible = false
        }
      })
    }
    this.article = store.getters.getArticle
    this.isUpdate = store.getters.getIsUpdate
    getAllTags().then((res) => {
      this.tags = res.data.data
    })
    this.categories = getAllCategory()
    console.log('===========请求到的分类信息')
    console.log(this.categories)
  },
  methods: {
    openMdFile() {
      openMdFIleLocal(this.article.id).then((res) => {
        this.$message.success('打开成功!')
      })
    },
    selectCategory() {
      this.article.category = this.article.category[1]
      this.showAddCategory = false
      this.article.newCategory = ''
    },
    // 处理图片加载失败
    handlerImgError(e) {
      e.target.src = require('../../assets/img/errorImg.jpeg')
    },
    // 图片的添加和删除
    $imgAdd(pos, file) {
      // 上传图片
      var formData = new FormData()
      formData.append('file', file)
      uploadImg(formData).then((url) => {
        Message({
          message: '上传成功!',
          type: 'success',
          duration: 3000
        })
        this.$refs.md.$img2Url(pos, url.data.data)
      })
        .catch(() => {
          this.$imgDel(pos)
        })
    },
    change(value, render) {
      this.html = render
    },
    $imgDel(pos) {
      delete this.img_file[pos]
    },
    // 图片上传
    beforeUpload() {

    },
    submitByUrl() {
      this.uploadingImg = true
      const updateImgByUrl = this.updateImgByUrl
      uploadImgByUrl(updateImgByUrl).then((res) => {
        this.$message.success('图片上传成功！')
        this.article.coverImg = res.data.data
      }).finally(() => {
        this.uploadingImg = false
      })
    },
    // 移除图片
    handleRemove() {
      this.article.coverImg = ''
    },
    // 上传成功的回调函数
    handleAvatarSuccess(res, file) {
      this.article.coverImg = res.data[0]
      this.uploadingImg = false
    },
    // 断言 判断需要填写的内容是否为空
    assertNotEmpty(target, msg) {
      if (!target) {
        this.$message({
          message: msg,
          type: 'warning'
        })
        return false
      }
      return true
    },
    // 打开文章信息填写框
    openDialog() {
      if (
        this.assertNotEmpty(this.article.title, '请填写文章标题') &&
        this.assertNotEmpty(this.article.content, '请填写文章内容')
      ) {
        this.showCreateDialog = true
      }
    },

    // 标签的方法
    // 删去选中的一个标签
    handleClose(tag) {
      this.article.tags.splice(this.article.tags.indexOf(tag), 1)
      if (this.article.tags.length < 5) {
        this.TagAddVisible = true
      }
    },
    // 展示输入新标签的名称
    showTagInput() {
      this.inputTagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    clickTag(item, index) {
      if (this.article.tags.indexOf(item.value) !== -1) {
        Message.info('该标签已经存在！')
        this.queryTag = ''
        return
      }
      if (this.article.tags.length > 4) {
        Message.info('最多只能选5个标签！')
        this.queryTag = ''
        return
      }
      this.article.tags.push(item.value)
      this.queryTag = ''
      if (this.article.tags.length === 5) {
        this.TagAddVisible = false
      }
    },
    // 确定需要创建该标签
    handleTagInputConfirm() {
      const inputValue = this.inputTag
      if (inputValue.length > 14) {
        Message.info('标签大小不能超过14个字符！')
        return
      }
      for (let i = 0; i < this.tags.length; ++i) {
        if (this.tags[i].toUpperCase() === inputValue.toUpperCase()) {
          Message.info(inputValue + '标签已经存在')
          return
        }
      }
      for (let i = 0; i < this.article.tags.length; ++i) {
        if (this.article.tags[i].toUpperCase() === inputValue.toUpperCase()) {
          Message.info(inputValue + '标签已经存在')
          return
        }
      }
      if (inputValue) {
        this.article.tags.push(inputValue)
        if (this.article.tags.length === 5) {
          this.TagAddVisible = false
        }
      }
      this.inputTagVisible = false
      this.inputTag = ''
    },
    // 搜索
    querySearchAsync: function(queryString, cb) {
      let results = []
      for (const i of this.tags) {
        results.push({ value: i })
      }
      console.log(results)
      results = queryString ? results.filter(this.createStateFilter(queryString)) : results
      cb(results)
    },
    // 过滤器
    createStateFilter(queryString) {
      return (item) => {
        return item.value.toUpperCase().match(queryString.toUpperCase())
      }
    },

    // 添加新文章至后端
    handleSubmit() {
      if (
        this.assertNotEmpty(this.article.tags.join(), '文章的标签不能为空') &&
        this.assertNotEmpty(this.article.category === '' ? this.article.newCategory : this.article.category, '文章的主题不能为空') &&
        this.assertNotEmpty(this.article.tabloid, '文章的摘要不能为空') &&
        this.assertNotEmpty(this.article.author, '文章的作者不能为空')
      ) {
        this.isUploading = true
        // 创建新的主题
        if (this.article.newCategory != null && this.article.category === '') {
          for (const category of this.categories) {
            for (const theme of category.children) {
              if (theme.label.toUpperCase() === this.article.newCategory.toUpperCase()) {
                Message.info('主题' + this.article.newCategory + '已存在')
                return
              }
            }
          }
          this.article.category = this.article.newCategory
          console.log('开始上传新的主题')
          this.beforeUploading = true
          createNewCategory(this.article.newCategory, null).then((res) => {
            Message.success(
              '上传主题' + this.article.newCategory + '成功！'
            )
          })
        }
        // 上传新的标签
        for (const tag of this.article.tags) {
          if (this.tags.includes(tag) === false) {
            this.beforeUploading = true
            createTag(tag).then((res) => {
              Message.success(
                '上传标签' + tag + '成功！'
              )
              this.beforeUploading = false
            })
          }
        }
        setTimeout(this.submitArticle, 1000)
      }
    },
    // 文章上传
    submitArticle() {
      if (this.article.type === '原创') {
        this.article.reprintURL = ''
      }
      this.showCreateDialog = false
      this.isActive = true
      // 存草稿
      if (this.article.status !== 'published') {
        if (!this.isUpdate) {
          uploadArticle(this.article).then(() => {
            this.$notify({
              title: '提示',
              message: `文章《${this.article.title}》以成功存为草稿`,
              type: 'success'
            })
            this.isActive = false
            store.commit('resetArticle')
            this.article = store.getters.getArticle
            this.isUpdate = store.getters.getIsUpdate
          }).finally(
            this.isUploading = false
          )
        } else {
          updateArticle(this.article).then(() => {
            this.$notify({
              title: '提示',
              message: `文章《${this.article.title}》更新成功,已经存入草稿`,
              type: 'success'
            })
            this.isActive = false
            store.commit('resetArticle')
            this.article = store.getters.getArticle
            this.isUpdate = store.getters.getIsUpdate
          }).finally(
            this.isUploading = false
          )
        }
      } else if (this.isUpdate === true) {
        updateArticle(this.article).then(() => {
          this.$notify({
            title: '提示',
            message: `文章《${this.article.title}》更新成功`,
            type: 'success'
          })
          this.isActive = false
          store.commit('resetArticle')
          this.article = store.getters.getArticle
          this.isUpdate = store.getters.getIsUpdate
        }).finally(
          this.isUploading = false
        )
      } else if (this.article.status === 'published') {
        uploadArticle(this.article).then(() => {
          this.$notify({
            title: '提示',
            message: `文章《${this.article.title}》发布成功`,
            type: 'success'
          })
          this.isActive = false
          store.commit('resetArticle')
          this.article = store.getters.getArticle
          this.isUpdate = store.getters.getIsUpdate
        }).finally(
          this.isUploading = false
        )
      }
    },
    reset() {
      this.$confirm('确定要退出更新模式回到创建页面吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.commit('resetArticle')
        this.article = store.getters.getArticle
        this.isUpdate = store.getters.getIsUpdate
        this.showCreateDialog = false
        this.$message.success('操作成功！')
      })
    }
  }
}
</script>
<style>
.main-window{
 position: relative;
}
.title-box {
  display: grid;
  grid-template-columns: 22fr 2fr;
  margin-left: 10px;
  margin-top: 20px;
}
#btn{
  margin-bottom: 17px;
  float: left;
}
.title {
  background: none;
  color: #303133;
  text-indent: 0px;
  outline: none;
  font-size: 16px;
  font-weight: bold;
  display: block;
  border: none;
  border-bottom: 1px solid #e0e0e0;
  border-radius: 0;
  line-height: 1;
  overflow: visible;
  margin-bottom: 15px;
  padding: 4px;
}
.title:focus {
  border-color: #409eff;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  vertical-align: bottom;
}
.toOpen {
  text-align: center;
  height: 30px;
  top: 50%;
  left: 50%;
  width: 100%;
  float: right;
}
.toOpen:hover{
  background-color: rgb(249,250,252);
  cursor:pointer ;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 310px;
  height: 198px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 310px;
  height: 198px;
  display: block;
}
</style>
